﻿define([
    'Xjs/core/util',
    'Xjs/core/builder',
    'Xjs/ui/View',
    'Xjs/core/Interactive',
    'Xjs/core/viewport'
],
function (util, builder, View, Interactive, viewport) {
    'use strict';

    var type = 'menuItem',
    MenuItem = Xjs.getType(type);

    if (MenuItem) { // It has been already loaded
        return MenuItem;
    }

    MenuItem = util.define({
        base: View, // Must use view to avoid cyclic references
        mixins: [
            Interactive
        ],
        construct: function (conf, parent) {

            MenuItem.base.constructor.call(this, conf, parent); // Call the base constructor

            Interactive.prototype.initialize.call(this, conf);

            this.handler = conf.handler;

            if (conf.menu) { // This menu items has a child menu
                this.menu = Xjs.create('menu', conf.menu, this);
                this.addChild(this.menu);
            }
        },
        requiresId: true,
        type: type,
        defaultChildType: 'menuItem',
        highlightable: true,
        selectable: true,

        onHighlight: function () {

            var menu = this.menu;

            if (menu) {

                menu.move(this.right(), this.top());
                viewport.adjust(menu.id); // Make sure it is completely visible inside the viewport
                menu.setVisible(true);
            }
        },

        onUnhighlight: function () {

            if (this.menu) {

                this.menu.setVisible(false);
            }
        },

        onSelect: function () {

            if (this.handler) {
                this.handler();
            }

            this.parent.setVisible(false);
        }

    });

    Xjs.registerType(MenuItem);

    return MenuItem;
});